﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using TreeViewWithViewModelDemo.FolderTree.DataModel;

namespace TreeViewWithViewModelDemo.FolderTree.ViewModel
{
    public class FolderNodeVIewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        readonly ReadOnlyCollection<FolderNodeVIewModel> _children;
        readonly FolderNodeVIewModel _parent;
        readonly MyFolder _folder;
        bool _isExpanded;
        bool _isSelected;

        public FolderNodeVIewModel(MyFolder person)
            : this(person, null)
        {
        }

        private FolderNodeVIewModel(MyFolder person, FolderNodeVIewModel parent)
        {
            _folder = person;
            _parent = parent;

            _children = new ReadOnlyCollection<FolderNodeVIewModel>(
                    (from child in _folder.Children
                     select new FolderNodeVIewModel(child, this))
                     .ToList<FolderNodeVIewModel>());
        }

        public ReadOnlyCollection<FolderNodeVIewModel> Children
        {
            get { return _children; }
        }
        public FolderNodeVIewModel Parent
        {
            get { return _parent; }
        }
        public string Name
        {
            get { return _folder.FloderName; }
        }


        public bool IsExpanded
        {
            get { return _isExpanded; }
            set
            {
                if (value != _isExpanded)
                {
                    _isExpanded = value;
                    this.OnPropertyChanged("IsExpanded");
                }

                // Expand all the way up to the root.
                if (_isExpanded && _parent != null)
                    _parent.IsExpanded = true;
            }
        }

        public bool IsSelected
        {
            get { return _isSelected; }
            set
            {
                if (value != _isSelected)
                {
                    _isSelected = value;
                    this.OnPropertyChanged("IsSelected");
                }
            }
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

    }
}
